package com.action;

import java.io.Serializable;
import java.util.Map;

import com.entity.User;
import com.service.CartService;
import com.service.Impl.CartServiceImpl;

import com.opensymphony.xwork2.ActionContext;

import com.entity.Cart;
import com.util.JedisUtil;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import redis.clients.jedis.Jedis;

@Controller
@Scope("prototype")
public class CartAction {
	@Autowired
	private CartService service;
	Map<String,Object>session = ActionContext.getContext().getSession();
	User user=(User)session.get("u");
	//Cart cart =(Cart)session.get("cart");
	private int bookId;
	private int count;
	private Cart c;

	public Cart getC() {
		return c;
	}

	public void setC(Cart c) {
		this.c = c;
	}

	public int getBookId() {
		return bookId;
	}
	public void setBookId(int bookId) {
		this.bookId = bookId;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public String showCart(){
		Jedis jedis = JedisUtil.getJedis();
		byte[] key = SerializationUtils.serialize(user.getUserId());
		byte[] cartByte = jedis.get(key);
		if(cartByte==null){
			c=new Cart();
		}
		c = (Cart) SerializationUtils.deserialize(cartByte);
		return "showCart";
	}
	public String showCart1(){
		Jedis jedis = JedisUtil.getJedis();
		byte[] key = SerializationUtils.serialize(user.getUserId());
		byte[] cartByte = jedis.get(key);
		c = (Cart) SerializationUtils.deserialize(cartByte);
		return "showCart1";
	}
	public void addCart(){
		Jedis jedis = JedisUtil.getJedis();
		byte[] key = SerializationUtils.serialize(user.getUserId());
		byte[] cartByte = jedis.get(key);
		if(cartByte==null){
			Cart cart=new Cart();
			byte[] value = SerializationUtils.serialize((Serializable)service.addCart(bookId, cart));
			jedis.set(key,value);
		}
		Cart cart = (Cart) SerializationUtils.deserialize(cartByte);
		byte[] value = SerializationUtils.serialize((Serializable)service.addCart(bookId, cart));
		jedis.set(key,value);
		//session.put("cart",service.addCart(bookId, cart));
	}
	public String updateCart(){
		Jedis jedis = JedisUtil.getJedis();
//		session.put("cart",service.updateCart(bookId, count, cart));
		return "updateCart";
	}
	public String deleteCart(){
		Jedis jedis = JedisUtil.getJedis();
//		session.put("cart",service.deleteCart(bookId, cart));
		return "deleteCart";
	}
	public String recoverCart(){
		Jedis jedis = JedisUtil.getJedis();
//		session.put("cart",service.recoverCart(bookId, cart));
		return "recoverCart";
	}
}
